package com.javaear.zblog4java.system.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.javaear.zblog4java.system.plugin.mybatisplus.GeneralMapper;
import com.javaear.zblog4java.system.service.IManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.javaear.zblog4java.system.plugin.mybatisplus.MapperContext;

import javax.servlet.http.HttpServletRequest;

/**
 * @author aooer
 */
@Service
public class ManagerService implements IManagerService {

    private static final String MNG_URL = "redirect:%s-management.html";
    private static final String EDT_URL = "system/edit/%s-edit";
    private static final String ADD_URL = "system/add/%s-add";

    @Autowired
    private MapperContext mapperContext;

    @Autowired
    private GeneralMapper generalMapper;

    @Override
    public void queryAll() {
        mapperContext.pickRequest().setAttribute("models", generalMapper.selectList(new EntityWrapper<>(mapperContext.pickModel())));
    }

    @Override
    public String add() {
        String type = mapperContext.pickRequest().getParameter("type");
        if (!StringUtils.isEmpty(type) && "show".equals(type))
            return typeFormat(ADD_URL);
        return generalMapper.insertSelective(mapperContext.pickModel()) > 0
                ? typeFormat(MNG_URL)
                : typeFormat(ADD_URL);
    }

    @Override
    public String edit() {
        HttpServletRequest request = mapperContext.pickRequest();
        String id = request.getParameter("id");
        if (StringUtils.isEmpty(id))
            return typeFormat(MNG_URL);
        String type = request.getParameter("type");
        if (!StringUtils.isEmpty(type) && "show".equals(type)) {
            request.setAttribute("model", generalMapper.selectById(Integer.parseInt(id),mapperContext.pickClass()));
            return typeFormat(EDT_URL);
        }
        return generalMapper.updateSelectiveById(mapperContext.pickModel()) > 0
                ? typeFormat(MNG_URL)
                : typeFormat(EDT_URL);
    }

    @Override
    public String remove() {
        String id = mapperContext.pickRequest().getParameter("id");
        if (!StringUtils.isEmpty(id))
            generalMapper.deleteById(Integer.parseInt(id),mapperContext.pickClass());
        return typeFormat(MNG_URL);
    }

    private String typeFormat(String url) {
        return String.format(url, mapperContext.pickType());
    }

}
